<template>
  <el-dialog
    v-model="visible"
    :title="$t('shop.accountManagement')"
    :close-on-click-modal="false"
    width="700px"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      :label-width="$t('language') === 'language' ? '160px' : '100px'"
      @keyup.enter="onSubmit()"
    >
      <!-- 商城名称 -->
      <el-form-item
        :label="$t('prodList.shopName')"
        prop="shopName"
      >
        <el-input
          v-model="dataForm.shopName"
          disabled
        />
      </el-form-item>

      <!-- 超管手机号 -->
      <el-form-item
        :label="$t('shop.merchantMobile')"
        prop="mobile"
      >
        <el-input
          v-model="dataForm.mobile"
          disabled
        />
      </el-form-item>

      <!-- 商城账号(用户名),唯一,可作为登录账号 -->
      <el-form-item
        :label="$t('shop.shopAccount')"
        prop="username"
      >
        <el-row style="width:100%">
          <el-col :span="19">
            <el-input
              v-model="dataForm.username"
              v-input-rule
              show-word-limit
              :placeholder="$t('shop.addShopErrorTip3')"
              :disabled="!editUsername"
            />
          </el-col>
          <el-col :span="5">
            <div
              v-if="!editUsername"
              class="default-btn text-btn"
              @click="changeEditUsername()"
            >
              {{ $t('platform.modifyAcc') }}
            </div>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item
        :label="$t('shop.loginPassword')"
        prop="password"
      >
        <el-input
          v-model="dataForm.password"
          v-input-rule
          type="password"
          maxlength="20"
          show-word-limit
          show-password
        />
      </el-form-item>

      <el-form-item
        :label="$t('sys.confirmPassword')"
        prop="checkPassword"
      >
        <el-input
          v-model="dataForm.checkPassword"
          v-input-rule
          type="password"
          maxlength="20"
          show-word-limit
          show-password
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div
        class="dialog-footer btn-row"
      >
        <div
          class="default-btn"
          @click="visible = false"
        >
          {{ $t('remindPop.cancel') }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="onSubmit()"
        >
          {{ $t('remindPop.confirm') }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { isUserName, validPassword } from '@/utils/validate.js'
import { ElMessage } from 'element-plus'

const emit = defineEmits(['refreshDataList'])

const editUsername = ref(false)
const dataForm = ref({
  shopId: 0,
  username: '',
  password: '',
  checkPassword: ''
})

const validateUsername = (rule, value, callback) => {
  if (!isUserName(value)) {
    callback(new Error($t('shop.InputCorrectUsername')))
  } else {
    http({
      url: http.adornUrl('/shop/shopAuditing/checkUsername'),
      method: 'get',
      params: http.adornParams({
        username: dataForm.value.username,
        shopId: dataForm.value.shopId
      })
    }).then(({ data }) => {
      if (data) {
        callback()
      } else {
        callback(new Error($t('shop.addShopErrorTip6')))
      }
    })
  }
}

const validatePassword = (rule, value, callback) => {
  if (!editUsername.value && !value) {
    callback(new Error($t('shop.loginPasswordTip')))
  } else if (!(editUsername.value && !value) && !validPassword(value)) {
    callback(new Error($t('passwordVerification')))
  } else {
    callback()
  }
}
const validateCheckPassword = (rule, value, callback) => {
  if (dataForm.value.password && !value) {
    callback(new Error($t('shop.againInput')))
  } else if (dataForm.value.password !== dataForm.value.checkPassword && dataForm.value.password !== null && dataForm.value.checkPassword !== null && dataForm.value.password !== undefined && dataForm.value.checkPassword !== undefined) {
    callback(new Error($t('shop.notEmptyTip10')))
  } else {
    callback()
  }
}

const dataRule = {
  username: [
    { required: true, message: $t('shop.errorTip11'), trigger: 'blur' },
    { validator: validateUsername, trigger: 'blur' }
  ],
  password: [
    { required: false, message: $t('sys.passwordNoNull'), trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' }
  ],
  checkPassword: [
    { required: false, message: $t('sys.confirmPassNoNull'), trigger: 'blur' },
    { validator: validateCheckPassword, trigger: 'blur' }
  ]
}

const visible = ref(false)
const dataFormRef = ref(false)
const init = (shopId) => {
  dataForm.value.shopId = shopId || 0
  visible.value = true
  nextTick(() => {
    dataFormRef.value?.resetFields()
    dataFormRef.value?.resetFields()
    editUsername.value = false
    dataForm.value.username = ''
    dataForm.value.password = ''
    dataForm.value.checkPassword = ''
    getDataInfo()
  })
}

const changeEditUsername = () => {
  editUsername.value = true
}

// 获取商城详情数据
const getDataInfo = () => {
  http({
    url: http.adornUrl('/platform/shopDetail/getMerchantInfo?shopId=' + dataForm.value.shopId),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    dataForm.value = data
  })
}

// 表单提交
const onSubmit = () => {
  dataFormRef.value?.validate((valid) => {
    if (valid) {
      if (!editUsername.value && !dataForm.value.password) {
        dataFormRef.value?.validateField('password')
      }
      if (!editUsername.value &&
        dataForm.value.password &&
        !dataForm.value.checkPassword) {
        dataFormRef.value?.validateField('checkPassword')
      }
      http({
        url: http.adornUrl('/platform/shopDetail/updateMerchantInfo'),
        method: 'put',
        data: http.adornData({
          shopId: dataForm.value.shopId,
          password: dataForm.value.password,
          username: dataForm.value.username
        })
      }).then(() => {
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1000,
          onClose: () => {
            visible.value = false
            emit('refreshDataList')
          }
        })
      })
    }
  })
}

const message = (msg) => {
  ElMessage({
    message: msg,
    type: 'error',
    duration: 1500
  })
}

defineExpose({
  init,
  message
})

</script>
